<template>
  <!-- 新增账号 表单 -->
  <a-modal
    v-model:open="visible"
    :title="isEdit ? '编辑账号' : '新增账号'"
    class="addStation"
    destroyOnClose
    :width="520"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="账号" name="account">
        <a-input
          v-model:value="form.account"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="用户名" name="username">
        <a-input
          v-model:value="form.username"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="手机号" name="phone">
        <a-input
          v-model:value="form.phone"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="邮箱" name="email">
        <a-input
          v-model:value="form.email"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="所属角色" name="roleIds">
        <!-- <a-cascader
          v-model:value="aaa"
          style="width: 100%"
          :options="roleList"
          multiple
          max-tag-count="responsive"
          placeholder="请选择"
          @change="changeRole"
        /> -->
        <a-tree-select
          v-model:value="form.roleIds"
          style="width: 100%"
          :tree-data="roleList"
          tree-checkable
          allow-clear
          :field-names="{
            label: 'name',
            value: 'id',
            children: 'childRoleList',
          }"
          :show-checked-strategy="SHOW_PARENT"
          placeholder="请选择"
          tree-node-filter-prop="label"
          @change="changeRole"
        />
      </a-form-item>
      <a-form-item label="所属部门" name="deptIds">
        <!-- <a-cascader
          :defaultValue="form.deptIds"
          style="width: 100%"
          multiple
          max-tag-count="responsive"
          :options="deptList"
          :field-names="{
            label: 'name',
            value: 'id',
          }"
          placeholder="请选择"
          @change="changeDept"
        ></a-cascader> -->
        <a-tree-select
          v-model:value="form.deptIds"
          style="width: 100%"
          :tree-data="deptList"
          tree-checkable
          allow-clear
          :show-checked-strategy="SHOW_PARENT"
          :field-names="{
            label: 'name',
            value: 'id',
          }"
          placeholder="请选择"
          tree-node-filter-prop="label"
          @change="changeDept"
        />
      </a-form-item>
      <a-form-item label="初始密码" v-if="!isEdit">
        <a-input
          v-model:value="form.password"
          class="formInput"
          placeholder="若不输入则自动生成，可重置"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import { Cascader } from 'ant-design-vue'
const $api = inject("$api")
const props = defineProps({
  addUserVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})
const loading = ref(false)
const visible = ref(props.addUserVisible)
const emits = defineEmits(["update:addUserVisible", "getUserList"])
watch(
  () => props.addUserVisible,
  (val) => {
    visible.value = val
    if (val) {
      getDeptTree()
      getRoleListAll()
      if (props.isEdit) {
        form.value = {
          ...props.rowData,
        }
      }
    }
  }
)
const labelCol = { style: { width: "100px" } }
const formRef = ref(null)
const roleList = ref([])
const deptList = ref([])
const form = ref({
  account: undefined,
  username: undefined,
  email: undefined,
  phone: undefined,
  roleIds: undefined,
  deptIds: undefined,
  password: undefined,
})
const options = [
  {
    label: "Light",
    value: "light",
    children: new Array(20)
      .fill(null)
      .map((_, index) => ({ label: `Number ${index}`, value: index })),
  },
  {
    label: "Bamboo",
    value: "bamboo",
    children: [
      {
        label: "Little",
        value: "little",
        children: [
          {
            label: "Toy Fish",
            value: "fish",
          },
          {
            label: "Toy Cards",
            value: "cards",
          },
          {
            label: "Toy Bird",
            value: "bird",
          },
        ],
      },
    ],
  },
]
const rules = ref({
  account: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  username: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  roleIds: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  deptIds: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
})

const cancel = () => {
  emits("update:addUserVisible", false)
  form.value = {
    account: undefined,
    username: undefined,
    email: undefined,
    phone: undefined,
    roleIds: undefined,
    deptIds: undefined,
    password: undefined,
  }
  formRef.value.clearValidate()
}
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const { password, ...other } = form.value

      const params = {
        ...form.value,
        roleIds: roleSelectedOptions.value,
        deptIds: deptSelectedOptions.value,
        userType: 1, // 1：内部用户 2：企业主账号 3：企业子账号-int
      }
      loading.value = true
      let res
      if (props.isEdit) {
        // 编辑带上id
        params.id = props.rowData.id
        const { password, ...other } = params
        res = await $api.userUpdate(other)
      } else {
        res = await $api.userAdd(params)
      }
      loading.value = false
      if (res.code === 0) {
        message.success(props.isEdit ? "编辑成功" : "新增成功")
        cancel()
        emits("getUserList")
      }
    })
    .catch((error) => {
      console.log("error", error)
    })
}
const getDeptTree = async () => {
  const res = await $api.deptTree()
  if (res.code === 0) {
    deptList.value = res.data
  }
}
const getRoleListAll = async () => {
  const res = await $api.roleListAll()
  if (res.code === 0) {
    roleList.value = res.data
  }
}
const roleSelectedOptions = ref([])
const changeRole = (val) => {
  roleSelectedOptions.value = val
}
const deptSelectedOptions = ref([])
const changeDept = (val) => {
  deptSelectedOptions.value = val
}
onMounted(() => {})
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 350px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
::v-deep(.ant-select-selector) {
  width: 350px !important;
}
</style>
